package com.cn.zengzeng.spbzengzeng.classload;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: ZhangZengZeng
 * @Date: 2023/3/13 18:07
 */
public class TestApplication extends ClassLoader{

    public static void main (String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        TestApplication testApplication = new TestApplication();
        Class<?> aClass = testApplication.findClass("D:\\tools\\idea\\project\\private-warehouse\\target\\classes\\com\\cn\\zengzeng\\spbzengzeng\\test\\DemoTest.class");
        Object instance = aClass.newInstance();
        Method getName = aClass.getMethod("show",null);
        getName.invoke(instance,null);
    }
    @Override
    protected Class<?> findClass (String name){
        byte[] result;
        try {
            FileInputStream fileInputStream = new FileInputStream(name);
            byte[] bytes = new byte[1024];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int temp = -1;
            while ((temp = fileInputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, temp);
            }
            fileInputStream.close();
            result = byteArrayOutputStream.toByteArray() ;
            byteArrayOutputStream.close() ;
        }catch(IOException e) {
            throw new RuntimeException(e);
        }
        return defineClass(null, result,0 , result.length) ;
    }
}
